﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Configuration;

namespace Badge_Manager.Controller
{
    public class Connector : IDisposable
    {
        private static Connector session;

        public static Connector Istance()
        {
            if (session == null)
                session = new Connector();
            return session;
        }

        public SqlConnection Connessione { get; private set; }

        private bool disposed = false;

        private Connector()
        {
            ApriConnessione();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    ChiudiConnessione();
                    session = null;
                }
                disposed = true;
            }
        }

        ~Connector()
        {
            Dispose(false);
        }

        private void ApriConnessione()
        {
            SqlConnectionStringBuilder build = new SqlConnectionStringBuilder();
            build.DataSource = Properties.Settings.Default.server.ToString();
            build.UserID = Properties.Settings.Default.utente.ToString();
            build.Password = Properties.Settings.Default.password.ToString();
            build.InitialCatalog = Properties.Settings.Default.nomedb.ToString();
            Connessione = new SqlConnection(build.ConnectionString);
            try
            {
                Connessione.Open();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Errore in sql" + ex.Message + "\n" + ex.StackTrace);
                return;
            }
        }

        private void ChiudiConnessione()
        {
            try
            {
                Connessione.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Errore: " + ex.Message + "\n" + ex.StackTrace);
                return;
            }
        }
    }
}